from typing import Dict, Any

import stripe

stripe.api_key = "sk_test_51Ogsw5B0IyqaSJBrwczlr820jnmvA1qQQGoLZ2XxOsIzikpmXo4pRLjw4XVMTEBR8DdVTYySiAv1XX53Zv5xqynF00GfMqttFd"


class SubscriptionService:
    def __init__(self):
        pass

    def create_subscription(self, customer_id, price_id) -> str:
        # 创建订阅
        subscription = stripe.Subscription.create(
            customer=customer_id,  # 客户 ID
            items=[{"price": price_id}],  # 价格 ID（需提前在 Stripe 控制台创建）
            payment_behavior="default_incomplete",  # 处理付款失败的策略
            expand=["latest_invoice.payment_intent"],  # 扩展返回付款意向信息
        )
        return subscription.id

    def get_subscription(self, subscription_id) -> Dict[str, Any]:
        subscription = stripe.Subscription.retrieve(subscription_id)
        return {
            "id": subscription.id,
            "status": subscription.status,  # 状态：active（活跃）、canceled（已取消）等
            "customer_id": subscription.customer,
            "currency": subscription.currency,
            "current_period_end": subscription.current_period_end  # 本期结束时间（时间戳）
        }

    def modify_subscription(self, subscription_id, new_price_id) -> str:
        """
        升级或者降级
        :param subscription_id:
        :param new_price_id:
        :return:
        """
        subscription = stripe.Subscription.modify(
            subscription_id,
            items=[{"price": new_price_id}],
            # 价格 ID（需提前在 Stripe 控制台创建）
            proration_behavior="create_prorations"  # 处理 prorated 费用（如中途变更的差价）
        )
        return subscription.id

    def delete_subscription(self, subscription_id) -> str:
        """
        立即取消订阅
        :param subscription_id:
        :return:
        """
        subscription = stripe.Subscription.delete(subscription_id)
        return subscription.id

    def cancel_subscription(self, subscription_id) -> str:
        """
        到期后自动取消
        :param subscription_id:
        :return:
        """
        canceled_sub = stripe.Subscription.modify(
            subscription_id,
            cancel_at_period_end=True
        )
        return canceled_sub.id


if __name__ == '__main__':
    customer_id = "cus_Swwsy7E2Os98L3"
    price_id1 = "price_1S1OpZB0IyqaSJBrE8CaW7q0"
    price_id2 = "price_1S1OpaB0IyqaSJBru0RzbXzo"
    service = SubscriptionService()
    subscription_id = service.create_subscription(customer_id, price_id1)
    subscription_id2 = service.modify_subscription(subscription_id, price_id2)
    print(subscription_id, subscription_id2)
    print(service.get_subscription(subscription_id))
    print(service.cancel_subscription(subscription_id))
    # print(service.delete_subscription(subscription_id))
